package com.cskaoyan.utils;


import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {


    static String url;
    static String username;
    static String password;
    static String driverClassName;

    static {

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driverClassName = properties.getProperty("driverClassName");
    }

    // 获取连接
    public static Connection getConnection(){
        Connection connection = null;

        try {
            // 加载驱动

            // 1. DriverManager.registerDriver(new Driver());
            // 2. new  Driver();
            // 3. Class.forName("com.mysql.jdbc.Driver");
            // 4. Class.forName(driverClassName);
            // 把驱动的全限定名称配置到配置文件中
            // 通过反射来加载驱动，可以解耦
            Class.forName(driverClassName);

            // 获取连接
            connection = DriverManager.getConnection(url, username, password);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

        return connection;

    }



    // 关闭资源  严格控制先后顺序，使用try ... finally
    // volatile  1. 内存可见性  2. 控制指令重排序
    public static void closeSource(Connection connection, Statement statement, ResultSet resultSet){

        try {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            try {
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

}
